package rlyy.framework.core.resolver.argument;

import com.alibaba.fastjson.JSONObject;
import rlyy.framework.core.common.request.FullRequest;
import rlyy.framework.core.common.utils.Base64Util;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.lang.reflect.Parameter;

@Component
public class FileMethodArgumentResolver implements MyHandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(Parameter parameter) {
        return parameter != null && MultipartFile.class.isAssignableFrom(parameter.getType());
    }

    @Override
    public Object resolveArgument(Parameter parameter, FullRequest fullRequest) throws Exception {
        JSONObject $file = fullRequest.getFile();
        if(CollectionUtils.isEmpty($file)){
            return null;
        }
        String fileName = $file.getString("File_Name");
        String fileContent = $file.getString("File_Content");
        ByteArrayInputStream bin = new ByteArrayInputStream(Base64Util.decodeByte(fileContent));
        MultipartFile multipartFile = new MockMultipartFile(fileName,fileName, MediaType.APPLICATION_OCTET_STREAM.toString(), bin);
        return multipartFile;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
